<?php

/**
 * TaxService.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-12 14:24:05
 * @modified   2023-05-12 14:24:05
 */

namespace Plugin\MultiSeller\Services\TotalServices;

use Beike\Admin\Repositories\TaxRateRepo;
use Beike\Seller\Repositories\SellerRepo;
use Beike\Shop\Services\CheckoutService;

class TaxService
{
    /**
     * @param CheckoutService $checkout
     * @return array|null
     */
    public static function getTotal(CheckoutService $checkout): ?array
    {
        $totalService = $checkout->totalService;
        $taxEnabled   = system_setting('base.tax', false);
        if (! $taxEnabled) {
            return null;
        }

        $allTaxes = $totalService->taxes;

        $totalItems = [];
        foreach ($checkout->totalService->getSellerIds() as $sellerId) {
            $taxes = $allTaxes[$sellerId];
            if ($sellerId == 0) {
                $sellerName = trans('MultiSeller::common.self');
            } else {
                $sellerName = SellerRepo::mapIdToStoreName()[$sellerId] ?? 'undefined';
            }
            foreach ($taxes as $taxRateId => $value) {
                if ($value <= 0) {
                    continue;
                }
                $totalItems[] = [
                    'seller_id'     => $sellerId,
                    'code'          => 'tax',
                    'title'         => TaxRateRepo::getNameByRateId($taxRateId) . '-' . $sellerName,
                    'amount'        => $value,
                    'amount_format' => currency_format($value),
                ];
                $totalService->amount += $value;
            }
        }

        $totalService->totals = array_merge($totalService->totals, $totalItems);

        return $totalItems;
    }
}
